package com.snowfeel.sfmall.core.utils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.snowfeel.sfmall.core.wrapper.BodyReaderHttpServletRequestWrapper;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author guomenghuai
 * @date 2024/7/20
 * @Description
 */
public class HttpUtils {
    /**
     * 获取全部参数(包括URL和Body上的)
     *
     * @param request
     * @return
     */
    public static Map<String, String> getAllParams(HttpServletRequest request) throws IOException {
        Map<String, String> paramsMap = new TreeMap<>();

        //获取parameters（对应@RequestParam）
        Map<String, String[]> requestParams = null;
        if (!CollectionUtils.isEmpty(request.getParameterMap())) {
            requestParams = request.getParameterMap();

            //获取GET请求参数,以键值对形式保存
            for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {//{username:[xx],password:[xx]}
                paramsMap.put(entry.getKey(), entry.getValue()[0]);
            }
        }

        // 分别获取了request inputstream中的body信息、parameter信息
        //获取body（对应@RequestBody）
        if (request instanceof BodyReaderHttpServletRequestWrapper) {
            BodyReaderHttpServletRequestWrapper requestWrapper = (BodyReaderHttpServletRequestWrapper) request;
            try {
                JSONObject data = JSONObject.parseObject(requestWrapper.getBody());
                //获取POST请求的JSON参数,以键值对形式保存
                for (Map.Entry<String, Object> entry : data.entrySet()) {
                    paramsMap.put(entry.getKey(), entry.getValue().toString());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return paramsMap;
    }
}
